package com.ruoyi.web.controller.app;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.douyin.openapi.client.Client;
import com.douyin.openapi.client.models.V2Jscode2sessionRequest;
import com.douyin.openapi.client.models.V2Jscode2sessionResponse;
import com.douyin.openapi.credential.models.Config;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.juhang.domain.User;
import com.ruoyi.juhang.domain.vo.AppLogin;
import com.ruoyi.juhang.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/app/login")
public class AppLoginController {

    @Value("${douyin.app.appId}")
    private String appId;

    @Value("${douyin.app.secret}")
    private String secret;

    @Autowired
    private IUserService userService;

    public V2Jscode2sessionResponse getOpenId(String code, String anonymousCode) {
        try{
            Config config = new Config().setClientKey(appId).setClientSecret(secret);
            Client client = new Client(config);
            V2Jscode2sessionRequest sdkRequest = new V2Jscode2sessionRequest();
            sdkRequest.setAnonymousCode(anonymousCode);
            sdkRequest.setAppid(appId);
            sdkRequest.setCode(code);
            sdkRequest.setSecret(secret);
            return client.V2Jscode2session(sdkRequest);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 抖音快捷登录
     * @param appLogin
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody AppLogin appLogin){
        V2Jscode2sessionResponse result = getOpenId(appLogin.getCode(), appLogin.getAnonymousCode());
        if (result == null){
            return AjaxResult.error("会话已过期");
        }
        String openId = result.getData().getOpenid();
        String unionid = result.getData().getUnionid();
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("open_id", openId);
        List<User> list = userService.list(queryWrapper);
        if(list.size() == 0){
            if(appLogin.getState() == 0){
                return AjaxResult.error("用户尚未注册-_-");
            }else {
                User user = new User();
                user.setOpenId(openId);
                user.setAvatarUrl(appLogin.getAvatarUrl());
                user.setNickName(appLogin.getNickName());
                user.setCreateTime(new Date());
                boolean save = userService.save(user);

                AjaxResult success = AjaxResult.success();
                success.put("data",user);
                return success;
            }
        }else {
            User user = list.get(0);
            AjaxResult success = AjaxResult.success("登陆成功");
            success.put("data",user);
            return success;
        }
    }
}
